<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>
                    <i class="el-icon-lx-cascades"></i> <span>{{ '用户信息' }}</span>
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div>
                <el-row :gutter="10" class="mb8">
                    <el-col :span="1.5">
                        <el-button type="primary" size="small" @click="handleAdd"
                        >新增管理员
                        </el-button>
                    </el-col>
                </el-row>
                <el-row>
                    <el-table
                            ref="multipleTableRef"
                            :data="userList"
                            style="width: 100%"
                            @selection-change="handleSelectionChange"
                            border
                    >
                        <el-table-column type="selection" width="55"/>
                        <el-table-column prop="userName" label="用户账号" align="center" width="120" >
                        </el-table-column>
                        <el-table-column prop="sex" label="用户性别" align="center" width="80"/>
                        <el-table-column prop="age" label="用户年龄" align="center" width="80"/>
                        <el-table-column prop="name" label="用户姓名" align="center" width="80"/>
                        <el-table-column prop="workType" label="工作种类" align="center" width="120">
                            <template v-slot="scope">
                                <span>{{ plantationType(scope.row.workType) }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="plantationName" label="管理园区" align="center" width="120" show-overflow-tooltip="true">
                            <template v-slot="scope">
                                <div v-for="item in scope.row.plantations">{{ item.plantationName }}</div>
                            </template>
                        </el-table-column>
                        <el-table-column prop="userPic" label="用户头像" align="center" width="180">
                            <template #default="scope">
                                <el-image class="table-td-thumb" :src="scope.row.userPic"
                                          :preview-src-list="[scope.row.userPic]">
                                </el-image>
                            </template>
                        </el-table-column>
                        <el-table-column prop="userEmail" label="工作邮箱" align="center" width="180" />
                        <el-table-column prop="userPhone" label="工作电话" align="center" width="150"/>
                        <el-table-column prop="userDetail" label="基本介绍" align="center" />
                        <el-table-column  label="操作" align="center" width="150">
                            <template #default="scope">
<!--                                <el-button type="text" icon="el-icon-plus"-->
<!--                                           @click="handleAddAdverse(scope.row.cropId)">新增不良事件-->
<!--                                </el-button>-->
                                <el-button type="text" icon="el-icon-edit" @click="handleEdit(scope.$index, scope.row)">编辑
                                </el-button>
                                <el-button type="text" icon="el-icon-delete" class="red"
                                           @click="handleDelete(scope.$index, scope.row)">删除
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-row>
            </div>
            <div class="pagination">
                <el-pagination background layout="total, prev, pager, next" :current-page="query.pageIndex"
                               :page-size="query.pageSize" :total="pageTotal"
                               @current-change="handlePageChange"></el-pagination>
            </div>
        </div>
        <!-- 新增作物弹出框 -->
        <el-dialog :title="title" v-model="open"  width="30%" append-to-body>
            <el-form label-width="70px" ref="form" :model="form" :rules="rules">
                <el-form-item label="用户账号" prop="username">
                    <el-input v-model="form.username"></el-input>
                </el-form-item>
                <el-form-item label="用户性别" prop="sex">
                    <el-radio-group v-model="form.sex">
                        <el-radio-button label="男">男</el-radio-button>
                        <el-radio-button label="女">女</el-radio-button>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="出生日期">
                    <el-col :span="11">
                        <el-date-picker type="date" placeholder="选择日期" v-model="form.age" style="width: 100%;"></el-date-picker>
                    </el-col>
                </el-form-item>
                <el-form-item label="用户姓名" prop="name">
                    <el-input v-model="form.name"></el-input>
                </el-form-item>
                <el-form-item label="工作种类" prop="workType">
                    <el-radio-group v-model="form.workType">
                        <el-radio-button label="1">种植园管理员</el-radio-button>
                        <el-radio-button label="2">养殖场管理员</el-radio-button>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="工作邮箱" prop="userEmail">
                    <el-input v-model="form.userEmail"></el-input>
                </el-form-item>
                <el-form-item label="工作电话" prop="userPhone">
                    <el-input v-model="form.userPhone"></el-input>
                </el-form-item>
                <el-form-item label="管理园区" prop="plantations">
                <el-checkbox-group v-model="form.plantationIds">
                    <el-checkbox-button
                            v-for="(item, index) in plantationList"
                            :key="index"
                            :label="item.plantationId"
                    >{{item.plantationName}}</el-checkbox-button>
                </el-checkbox-group>

                </el-form-item>
                <el-form-item label="个人简介" prop="userDetail">
                    <el-input type="textarea" v-model="form.userDetail"></el-input>
                </el-form-item>
                <el-form-item label="作物照片" prop="userPic">
                    <el-upload
                            class="avatar-uploader"
                            action="http://localhost:8001/AgriculturalBigData/upload/img"
                            :show-file-list="false"
                            :on-success="handleAvatarSuccess"
                            :before-upload="beforeAvatarUpload">
                        <img v-if="imageUrl!=''" :src="imageUrl" class="avatar">
                        <i v-else class="el-icon-plus avatar-uploader-icon">上传图片</i>
                    </el-upload>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="open = false">取 消</el-button>
                    <el-button type="primary" @click="submit">确 定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script>
    import {ref, reactive} from "vue";
    import {ElMessage, ElMessageBox} from "element-plus";
    import {getUserList,addUser,getPlantationList} from "../api/index.js";
    import { useRouter,useRoute } from "vue-router";

    export default {
        name: "userManage",
        components: {},
        data() {
            return {
                imageUrl:'',
                plantationList:[],
                title:'',
                userList: [],
                plantationName:'',
                plantationId:'',
                pageTotal: 0,
                cropId:'',
                open:false,
                openCrop:false,
                form:{
                    plantationIds:[],
                },
                rules:{

                },
            }
        },
        created() {
            // 通过id获取用户所有信息
            this.getUserList();
            // 获取所有园区信息
            getPlantationList().then(res => {
                this.plantationList = res.rows;
            })
        },
        methods: {

            getUserList() {
                getUserList().then(res => {
                    this.userList = res.rows;
                    this.pageTotal = res.total;
                })
            },
            // 种植园类型转换
            plantationType(status) {
                if (status == 0) {
                    return "超级管理员"
                } else if (status == 1) {
                    return "种植园管理员"
                } else if (status == 2) {
                    return "养殖场管理员"
                }
            },
            handleSelectionChange() {
            },
            handleEdit() {
            },
            handleDelete() {
            },
            handleAdd() {
                console.log(this.plantationList)
                this.open = true;
                this.title = "添加管理员信息";
            },
            //图片回显
            handleAvatarSuccess(res, file) {
                // console.log(res)
                this.imageUrl = res.msg;
                // sessionStorage.setItem("imgUrl",this.imageUrl)
                // alert(this.imageUrl)
            },
            //图片上传大小限制
            beforeAvatarUpload(file) {
                const isLt2M = file.size / 1024 / 1024 < 2;
                if (!isLt2M) {
                    ElMessage.error('上传头像图片大小不能超过 2MB!');
                }
                return isLt2M;
            },
            submit() {
                if (this.form.userId != null) {
                    // console.log("------------表单内容------------");
                    // console.log(this.form);
                    // updatePlan(this.form).then(response => {
                    //     this.msgSuccess("修改成功");
                    //     this.open = false;
                    //     this.getList();
                    // });
                } else {
                    this.form.userPic = this.imageUrl;
                    console.log("------------表单内容------------");
                    console.log(this.form);
                    addUser(this.form).then(response => {
                        ElMessage.success("新增成功");
                        this.open = false;
                        this.getUserList();
                    }).catch((err) => {
                        // this.loading = false
                        console.log(err);
                    });
                }
            },
            // 获取园区名称
            getPlantationName() {
                // console.log(this.plantationName)
                return this.plantationName;
            },
        },
        setup() {
            const query = reactive({
                address: "",
                name: "",
                pageIndex: 1,
                pageSize: 10,
            });
            const tableData = ref([]);
            const pageTotal = ref(0);
            // 获取表格数据
            const getData = () => {
                // fetchData(query).then((res) => {
                //     tableData.value = res.list;
                //     pageTotal.value = res.pageTotal || 50;
                // });
            };
            getData();

            // 查询操作
            const handleSearch = () => {
                query.pageIndex = 1;
                getData();
            };
            // 分页导航
            const handlePageChange = (val) => {
                query.pageIndex = val;
                getData();
            };

            // 删除操作
            const handleDelete = (index) => {
                // 二次确认删除
                ElMessageBox.confirm("确定要删除吗？", "提示", {
                    type: "warning",
                })
                    .then(() => {
                        ElMessage.success("删除成功");
                        tableData.value.splice(index, 1);
                    })
                    .catch(() => {
                    });
            };

            // // 表格编辑时弹窗和保存
            // const editVisible = ref(false);
            // let form = reactive({
            //     name: "",
            //     address: "",
            // });
            // let idx = -1;
            // const handleEdit = (index, row) => {
            //     idx = index;
            //     Object.keys(form).forEach((item) => {
            //         form[item] = row[item];
            //     });
            //     editVisible.value = true;
            // };
            // const saveEdit = () => {
            //     editVisible.value = false;
            //     ElMessage.success(`修改第 ${idx + 1} 行成功`);
            //     Object.keys(form).forEach((item) => {
            //         tableData.value[idx][item] = form[item];
            //     });
            // };
            const router = useRouter();
            const forward = () => {
                router.push({
                    path: '/crop',
                    query: {

                    }
                })
            }
            return {
                query,
                tableData,
                pageTotal,
                // editVisible,
                // form,
                handleSearch,
                handlePageChange,
                handleDelete,
                // handleEdit,
                forward,
                // saveEdit,
            };
        },
    };
</script>

<style scoped>
    .handle-box {
        margin-bottom: 20px;
    }

    .handle-select {
        width: 120px;
    }

    .handle-input {
        width: 300px;
        display: inline-block;
    }

    .table {
        width: 100%;
        font-size: 14px;
    }

    .red {
        color: #ff0000;
    }

    .mr10 {
        margin-right: 10px;
    }

    .table-td-thumb {
        display: block;
        margin: auto;
        width: 40px;
        height: 40px;
    }
</style>